import React, { memo, useCallback, useEffect, useState } from 'react'
import { shallowEqual, useDispatch, useSelector } from 'react-redux'
import { AllAlbumsWrapper, ContentWrapper ,NavWrapper} from './style'
import { getAllAlbumsAction } from '../../store/actionCreators'
import {albumsCategories} from '@/services/local-data'
import { formatImg } from '@/utils/format'
import Page from '@/components/page'
import useShowAlbumDetail from '@/hooks/useShowAlbumDetail'
export default memo(function AllAlbums() {
  const dispatch = useDispatch()
  const [offset, setOffset] = useState(0)
  const [area, setArea] = useState('ALL')
  useEffect(() => {
    dispatch(getAllAlbumsAction(area,offset))
  }, [dispatch,offset,area])
  const { allAlbums,allCount} = useSelector(state => ({
    allAlbums: state.getIn(['album', 'allAlbums']),
    allCount:state.getIn(['album','allCount'])
  }), shallowEqual)
  const pageChange = useCallback(page => {
    const currentOffset = (page - 1) * 35
    setOffset(currentOffset)
    dispatch(getAllAlbumsAction(area,currentOffset))
  }, [dispatch,area])
  const chooseArea = area => {
    console.log(area);
    setArea(area)
    dispatch(getAllAlbumsAction(area,offset))
  }
  const goToAlbumDetail = useShowAlbumDetail()
  const albums = allAlbums || []
  return (
    <AllAlbumsWrapper>
      <NavWrapper>
        <h2 className='title'>全部新碟</h2>
        <div className="cats">
          {
            albumsCategories.map(item => {
              return (
                <span className="cat" key={item.area} onClick={e => chooseArea(item.area)}>{item.title}</span>
              )
            })
          }
        </div>
      </NavWrapper>
      <ContentWrapper>
        {
          albums.map(item => {
            return (
              <div className="item" key={item.id} onClick={e => goToAlbumDetail(item.id)}>
                 <img src={formatImg(item.picUrl,130)} alt="" className="image"/>
                <div className="mask sprite_covor"></div>
                <div className="name text-nowrap">{item.name}</div>
                <div className="artist text-nowrap">{item.artist.name}</div>
                <div className="play sprite_icon"></div>
              </div>
            )
          })
        }
      </ContentWrapper>
      <Page totalCount={allCount} pageSize={35} pageChange={pageChange}/>
    </AllAlbumsWrapper>
  )
})
